﻿#include "../../inc/helper.hpp"

const static char* g_msg_worker_ready = "\001";

int main()
{
	zmq::context_t ctx;
	zmq::socket_t frontend(ctx, zmq::socket_type::router);
	zmq::socket_t backend(ctx, zmq::socket_type::router);
	frontend.bind("tcp://*:5555");
	backend.bind("tcp://*:5556");

	std::vector<zmq::pollitem_t> items = {
		{backend, 0, ZMQ_POLLIN, 0},
		{frontend, 0, ZMQ_POLLIN, 0}
	};
	std::list<zmq::message_t> worker_queue;
	while (true)
	{
		/// 没有工作线程时，不需要考虑从前端获取请求
		if (worker_queue.empty()) {
			zmq::poll(items.data(), 1);
		}
		else {
			zmq::poll(items);
		}

		if (items[0].revents & ZMQ_POLLIN)
		{
			/// 获取worker id
			auto replies = zmsg_recv(backend);

			/// 添加到可用worker列表中
			worker_queue.push_back(std::move(replies[0]));

			if (to_string(replies.back()) != g_msg_worker_ready)
			{
				/// 如果是消息回复，转发到前端
				replies.erase(replies.begin(), replies.begin() + 2);
				zmsg_send(frontend, replies);
			}
		}
		else if (items[1].revents & ZMQ_POLLIN)
		{
			auto requests = zmsg_recv(frontend);

			std::vector<zmq::message_t> msgs;
			msgs.emplace_back(std::move(worker_queue.front()));
			msgs.emplace_back();
			for (auto& msg : requests)
			{
				msgs.emplace_back(std::move(msg));
			}
			zmsg_send(backend, msgs.begin(), msgs.end());

			worker_queue.pop_front();
		}
	}
}